<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="110px">
         <el-form-item label="检查名称:">
            <el-input v-model="queryParams.governCheckTaskName" placeholder="请输入检查名称" clearable
               @keyup.enter="handleQuery" />
         </el-form-item>
         <!--
         <el-form-item label="检查单位:">
            <el-input v-model="queryParams.governCheckCompany" placeholder="请输入检查单位" clearable
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="检查类型:">
            <el-select v-model="queryParams.governCheckTaskTypeName" placeholder="请选择检查类型" clearable>
               <el-option v-for="value in taskTypeList" :key="value" :label="value" :value="value" />
            </el-select>
         </el-form-item>
         <el-form-item label="检查人员:">
            <el-input v-model="queryParams.governCheckUserNames" placeholder="请输入检查人员" clearable
               @keyup.enter="handleQuery" />
         </el-form-item>
		 -->
         <el-form-item label="检查日期:">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
               start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-card class="card-box">
         <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column label="序号" width="55" type="index" align="center" prop="planId" fixed="left" />
            <el-table-column label="检查名称" align="center" prop="governCheckTaskName" width="320"
               :show-overflow-tooltip="true" />
            <el-table-column label="涉及危险源" align="center" prop="governInvolveDanger" :show-overflow-tooltip="true"
               width="150" />
            <el-table-column label="检查类型" align="center" prop="governCheckTaskTypeName" width="100" />
            <el-table-column label="计划开始日期" align="center" prop="governTaskStartTime" width="120" />
            <el-table-column label="计划结束日期" align="center" prop="governTaskEndTime" width="120" />
            <el-table-column label="登记时间" align="center" prop="governTaskRegisterTime" width="160" />
            <el-table-column label="检查人员" align="center" prop="governCheckUserNames" width="160" />
            <el-table-column label="检查状态" align="center" prop="governPlanStatus">
               <template v-slot="scope">
                  {{ scope.row.governPlanStatus === 0 ? '暂存' : '已提交' }}
               </template>
            </el-table-column>
            <el-table-column label="检查单位" align="center" prop="governCheckCompany" />

            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
               <template #default="scope">
                  <el-button type="text" icon="view" @click="handleView(scope.row)"
                     v-hasPermi="['check:governCheckTaskPlan:query']">查看</el-button>
                  <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['check:governCheckTaskPlan:edit']">编辑</el-button>
                  <el-button type="text" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['check:governCheckTaskPlan:remove']">删除</el-button>
               </template>
            </el-table-column>
         </el-table>
         <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>

      <!-- 详情对话框 -->
      <el-dialog :title="title" v-model="detailOpen" width="55%" append-to-body>
         <el-form ref="planDetail" :model="formDetail" :rules="rules" label-width="150px" style="margin-right: 90px">
            <el-row>
               <el-col :span="12">
                  <el-form-item label="检查名称" prop="governCheckTaskName">
                     <el-input v-model="formDetail.governCheckTaskName" placeholder="请输入检查名称" clearable
                        :disabled=true />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="检查类型" prop="governCheckTaskTypeName">
                     <el-select v-model="formDetail.governCheckTaskTypeName" placeholder="请选择检查类型" clearable
                        :disabled=true style="width: 100%;">
                        <el-option v-for="value in taskTypeList" :key="value" :label="value" :value="value" />
                     </el-select></el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="检查来源">
                     <el-input v-model="formDetail.governCheckSource" placeholder="请输入检查来源" :disabled=true />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="检查级别">
                     <el-input v-model="formDetail.governCheckLevel" placeholder="请输入检查级别" clearable :disabled=true />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="开始时间">
                     <el-date-picker v-model="formDetail.governTaskStartTime" type="date" placeholder="选择日期"
                        :disabled=!flag style="width: 100%;" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="结束时间">
                     <el-date-picker v-model="formDetail.governTaskEndTime" type="date" placeholder="选择日期"
                        :disabled=!flag style="width: 100%;" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col>
                  <el-form-item label="检查人员">
                     <el-input v-model="formDetail.governCheckUserNames" @click="onInnerOpen" :disabled="!flag"
                        readonly />
                  </el-form-item>
                  <TableSelect ref="userTableSelect" :queryApi="listUser" :options="[]" :rowKey="'userId'"
                     rowLabel="nickName" @onConfirm="onUserConfirm" rowLabelText="用户昵称" :maxNum="10">
                     <template #formSlot="{ handleQuery, filterForm }">
                        <el-col :span="8">
                           <el-form-item label="部门名称">
                              <el-input size="small" @change="handleQuery" v-model="filterForm.deptName" clearable
                                 style="width: 100%" @keyup.enter="handleQuery" />
                           </el-form-item>
                        </el-col>
                        <el-col :span="8">
                           <el-form-item label="用户名称">
                              <el-input size="small" @change="handleQuery" v-model="filterForm.userName" clearable
                                 style="width: 100%" @keyup.enter="handleQuery" />
                           </el-form-item>
                        </el-col>
                     </template>
                     <template #tableSlot>
                        <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" />
                        <el-table-column label="用户名称" align="center" key="userName" prop="userName" />
                        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" />
                     </template>
                  </TableSelect>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="文件上传" prop="fileId" :disabled="!flag">
                     <FileUpload :limit="1" :fileSize="30" v-model="files" style="width: 100%;" :disabled="!flag" />
                  </el-form-item>
               </el-col>
            </el-row>

            <el-form-item style="position: absolute; top: 40px; right: 50px;" v-if="flag">
               <el-button type="primary" @click="submitForm('Save')">暂存</el-button>
               <el-button type="primary" @click="submitForm('Release')">提交并保存</el-button>
            </el-form-item>
         </el-form>
         <el-card class="card-box">
            <template #header v-if="flag">
               <span style="display: flex; justify-content: flex-end;">
                  <el-button type="primary" @click="getCheckUsers" :disabled="multiple">批量分配</el-button>
                  <el-button type="primary" @click="resetAllocation">重置分配</el-button>
                  <el-button type="warning" plain icon="Upload" @click="importCheckUser">导入导出用户</el-button>
               </span>
            </template>
            <el-table v-loading="loading" :data="governCheckTaskPlanItemList"
               @selection-change="handleSubSelectionChange">
               <el-table-column type="selection" width="40" align="center" fixed="left" />
               <el-table-column label="序号" width="55" type="index" align="center" prop="taskId" fixed="left" />
               <el-table-column label="检查项目" align="center" width="250" :show-overflow-tooltip="true">
                  <template #default="scope">
                     {{ scope.row.governCheckName + scope.row.governCheckContent }}
                  </template>
               </el-table-column>
               <el-table-column label="检查方式" align="center" prop="governCheckWay" width="250"
                  :show-overflow-tooltip="true" />
               <el-table-column label="检查依据" align="center" prop="governCheckBasis" width="250"
                  :show-overflow-tooltip="true" />
               <el-table-column label="适用场合" align="center" prop="governApplicablePlace" width="250"
                  :show-overflow-tooltip="true" />
               <el-table-column label="检查人员" align="center" prop="governCheckUserName" width="150" fixed="right"
                  :show-overflow-tooltip="true" />
               <el-table-column v-if="flag" label="操作" align="center" width="200" fixed="right"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-button type="text" icon="user" @click="getCheckUsers(scope.row, 'user')"
                        v-hasPermi="['check:governCheckTaskPlan:user']">分配检查人员</el-button>
                     <el-button type="text" icon="delete" @click="handleDeleteItem(scope.row)"
                        v-hasPermi="['check:governCheckTaskPlan:delete']">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
            <pagination v-show="total1 > 0" :total="total1" v-model:page="queryParams.pageNum1"
               v-model:limit="queryParams.pageSize1" @pagination="getTaskPlanItemList" />
         </el-card>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <!--    <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div> -->
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                     @click="exportCheckUser">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 分配检查人员对话框 -->
      <el-dialog :title="userTitle" v-model="userOpen" width="55%" append-to-body>
         <el-card class="card-box">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" style="margin: 20px 0;"
               @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="checkedUsers" @change="handleCheckedCitiesChange">
               <el-checkbox v-for="user in userOptions" :label="user" :key="user.userId">{{
                  user.nickName
               }}</el-checkbox>
            </el-checkbox-group>
         </el-card>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="updateCheckUser">确 定</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="GovernCheckTaskPlan">
import { getCheckType } from "@/api/check/governCheckTaskInfo";
import { listGovernCheckTaskPlan, getGovernCheckTaskPlan, delGovernCheckTaskPlan, checkUsersCheckTaskPlan, updateGovernCheckTaskPlan } from "@/api/check/governCheckTaskPlan";
import { listGovernCheckTaskPlanItem, batchUpdate, resetCheckUser, delGovernCheckTaskPlanItem } from "@/api/check/governCheckTaskPlanItem";
import { listUser } from "@/api/system/user";
import TableSelect from "@/components/tableSelect/index";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const planList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const total1 = ref(0);
const title = ref("");
const userTitle = ref("");
const dateRange = ref([]);
const taskTypeList = ref([]);
const governTaskPlanId = ref();

const governCheckTaskPlanItemList = ref([]);

// 详情模态框
const detailOpen = ref(false);
const userOpen = ref(false);
const files = ref([]);
const flag = ref(true);
const userTableSelect = ref();
const userType = ref("");
const multiple = ref(true);
const itemIds = ref([]);

// 上传
/*** 用户导入参数 */
const upload = reactive({
   // 是否显示弹出层（用户导入）
   open: false,
   // 弹出层标题（用户导入）
   title: "",
   // 是否禁用上传
   isUploading: false,
   // 是否更新已经存在的用户数据
   updateSupport: 0,
   // 设置上传的请求头部
   headers: { Authorization: "Bearer " + getToken() },
   // 上传的地址
   url: '/dev-api/check/governCheckTaskPlanItem/importData',
});



// 分配检查人员
const checkAll = ref(false);
const checkedUsers = ref([]);
const userOptions = ref([]);
const isIndeterminate = ref(false);

const onInnerOpen = () => {
   const {
      governCheckUserIds,
      governCheckUserNames,
   } = formDetail.value;
   let values = (governCheckUserIds && governCheckUserIds.split(",")) || [];
   let names = (governCheckUserNames && governCheckUserNames.split(",")) || [];
   userTableSelect.value.open(
      values.map((item, index) => ({
         value: values[index],
         label: names[index],
      }))
   );
};
const onUserConfirm = (data) => {
   const values = data.map((item) => item.value).join(",");
   const names = data.map((item) => item.label).join(",");
   formDetail.value.governCheckUserIds = values;
   formDetail.value.governCheckUserNames = names;
};

const data = reactive({
   formDetail: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      pageNum1: 1,
      pageSize1: 10,
      governCheckTaskName: undefined,
      governCheckCompany: undefined,
	  governCheckTaskTypeName: '企业自查'
   },
   rules: {
      governCheckTaskName: [{ required: true, message: "检查名称不能为空", trigger: "blur" }],
      governCheckCompany: [{ required: true, message: "检查单位不能为空", trigger: "blur" }],
      configValue: [{ required: true, message: "参数键值不能为空", trigger: "blur" }]
   }
});

const { queryParams, formDetail, rules } = toRefs(data);

function getCheckUsers(data, type) {
   checkedUsers.value = [];
   loading.value = true;
   checkUsersCheckTaskPlan(governTaskPlanId.value).then(response => {
      userOptions.value = response.data;
      loading.value = false;
      userOpen.value = true;
      userTitle.value = "配分检查人员";
   });
   userType.value = type;
   if (type === 'user') {
      itemIds.value = [];
      itemIds.value.push(data.governTaskPlanItemId);
   }
}
function handleCheckAllChange(val) {
   checkedUsers.value = val ? userOptions.value : [];
   isIndeterminate.value = false;
}
function handleCheckedCitiesChange(value) {
   console.log(value);
   const checkedCount = value.length;
   checkAll.value = checkedCount === userOptions.value.length;
   isIndeterminate.value = checkedCount > 0 && checkedCount < userOptions.value.length;
}
function updateCheckUser() {
   if (userType.value !== 'user') {
      itemIds.value = ids.value;
   }
   const list = [];
   const userNames = checkedUsers.value?.map((item) => item.nickName).join(",");
   const userIds = checkedUsers.value?.map((item) => item.userId).join(",");
   console.log(checkedUsers.value);
   console.log(userIds);

   itemIds.value.forEach((item) => {
      list.push({
         governTaskPlanItemId: item,
         governCheckUserId: userIds,
         governCheckUserName: userNames
      })
   })
   batchUpdate(list).then(response => {
      getTaskPlanItemList(governTaskPlanId.value);
   });
   userOpen.value = false;
}


/** 查询检验类型列表 */
function getCheckTypeList() {
   loading.value = true;
   getCheckType().then(response => {
      taskTypeList.value = response.data;
      loading.value = false;
   });
}

/** 计划多选数据 */
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.governTaskPlanId);
}
/** 计划子项多选数据 */
function handleSubSelectionChange(selection) {
   ids.value = selection.map(item => item.governTaskPlanItemId);
   multiple.value = !selection.length;
}

/** 查询参数列表 */
function getList() {
   loading.value = true;
   listGovernCheckTaskPlan(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
      planList.value = response.rows;
      total.value = response.total;
      loading.value = false;
   });
}

/** 查看按钮操作 */
function handleView(row) {
   reset();
   flag.value = false;
   const id = row.governTaskPlanId || ids.value;
   getGovernCheckTaskPlan(id).then(response => {
      formDetail.value = response.data;
      formDetail.value.governCheckSource = '专项检查';
      detailOpen.value = true;
      title.value = "查看计划";
   });

   queryParams.value.pageNum1 = 1;
   governTaskPlanId.value = id;
   getTaskPlanItemList();
}

/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   flag.value = true;
   const id = row.governTaskPlanId || ids.value;
   getGovernCheckTaskPlan(id).then(response => {
      formDetail.value = response.data;
      formDetail.value.governCheckSource = '专项检查';
      formDetail.value.governTaskPlanId = id;
      detailOpen.value = true;
      title.value = "修改计划";
   });

   queryParams.value.pageNum1 = 1;
   governTaskPlanId.value = id;
   getTaskPlanItemList();
}

/** 查询参数列表 */
function getTaskPlanItemList() {
   loading.value = true;
   const params = {
      pageNum: queryParams.value.pageNum1,
      pageSize: queryParams.value.pageSize1,
      governTaskPlanId: governTaskPlanId.value,
   }
   listGovernCheckTaskPlanItem(params).then(response => {
      governCheckTaskPlanItemList.value = response.rows;
      total1.value = response.total;
      loading.value = false;
   });
}

/** 表单重置 */
function reset() {
   formDetail.value = {
      governTaskPlanId: null,
   };
   proxy.resetForm("planDetail");
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   dateRange.value = [];
   proxy.resetForm("queryRef");
   getTaskPlanItemList();
}

/** 提交按钮 */
function submitForm(type) {
   loading.value = true;
   proxy.$refs["planDetail"].validate(valid => {
      if (valid) {
         if (type === 'Release') {
            formDetail.value.governPlanStatus = 1;
         } else {
            formDetail.value.governPlanStatus = 0;
         }
         updateGovernCheckTaskPlan(formDetail.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            // detailOpen.value = false;
            governTaskPlanId.value = null;
            getList();
         });
         loading.value = false;
      }
   });
}

/** 重置分配 */
function resetAllocation() {
   loading.value = true;
   resetCheckUser(governTaskPlanId.value).then(response => {
      proxy.$modal.msgSuccess("重置成功");
      getTaskPlanItemList();
      loading.value = false;
   });

}

function importCheckUser() {
   upload.title = "用户导入";
   upload.open = true;
}
function exportCheckUser() {
   proxy.download(
      '/check/governCheckTaskPlanItem/export/' + governTaskPlanId.value,
      {},
      `template_${new Date().getTime()}.xlsx`
   );
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
   upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
   upload.open = false;
   upload.isUploading = false;
   proxy.$refs["uploadRef"].handleRemove(file);
   proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;word-wrap: break-word;'>" +
      response.msg +
      "</div>",
      // "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      // // response.msg  +
      // response.msg.replace(/(.{1,100})/g, "$1<br>") +
      // "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
   );
   getTaskPlanItemList();
};
/** 提交上传文件 */
function submitFileForm() {
   proxy.$refs["uploadRef"].submit();
}
/** 删除子计划项 */
function handleDeleteItem(row) {
   const id = row.governTaskPlanItemId;
   proxy.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(function () {
      return delGovernCheckTaskPlanItem(id);
   }).then(() => {
      getTaskPlanItemList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}


/** 删除按钮操作 */
function handleDelete(row) {
   // const id = row.governTaskPlanId || ids.value;
   const id = row.governTaskPlanId;
   proxy.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(function () {
      return delGovernCheckTaskPlan(id);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
};

getList();
getCheckTypeList();
</script>
